<template>
  <div style="margin-top: 12px">
    <search-filed :searchList="searchListArr" :selectField="searchFieldTmp" @clear="clearSearch" @close="closeOneField"/>
    <a-table size="middle" class="AcctTable" :rowKey="record=>record.id" style="margin-top: 12px" :scroll="{ x: 1000 }"
      :columns="columns" :dataSource="data"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps}"
      :rowClassName="setRowClassName"
      :pagination="{onChange: changePage, ...pagination}" :loading="loading">
      <template slot="title" >
        <TableOperate ref="TableOperate" :valueFileds="valueFileds"
        :searchList="searchListArr" :searchTitle="$route.name === 'activityList' ? '活动名称' : '名称'" :operateBtn="getBtn"
        @searchFormValue="searchFormValue" :noDate="true"  @batchOperation="(id)=> updateStatus(id, selectedRowKeys)"
        />
      </template>
      <template slot="name" slot-scope="text, record">
        <p class="updateText info_text cursor" :record="record" @click="toDetail(record)">{{record.title || record.name}}</p>
      </template>
      <template slot="dateCreated" slot-scope="text, record">
        <p :record="record">{{moment(text).format('YYYY-MM-DD HH:mm:ss')}}</p>
      </template>
      <template slot="status" slot-scope="text">
        <p v-if="text === 'NEW'">待发布</p>
        <p v-else-if="text === 'PUBLISHED'">已发布</p>
        <p v-else-if="text === 'REVOKE'">已下线</p>
        <p v-else>{{ text }}</p>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button type="primary" size="small" v-if="record.status === 'NEW' || record.status === 'REVOKE'" @click="toActivityEdit(record.id)">编辑</a-button>
        <a-button type="primary" size="small" v-if="record.status === 'NEW' || record.status === 'REVOKE'" @click="updateAuditStatus('PUBLISHED', [record.id])">发布</a-button>
        <a-button type="danger" size="small" v-if="record.status === 'PUBLISHED'" @click="updateAuditStatus('REVOKE', [record.id])">下线</a-button>
      </template>
    </a-table>
  </div>
</template>

<script>
import moment from 'moment'
import TableOperate from '@/components/SearchList/TableOperate'
import SearchFiled from '@/components/SearchList/SearchFiled'
import { changeActivityStatus, changePicStatus, changeVideoStatus, changeIntroStatus, changeInstitutionStatus } from '@/api/config'
// import { selectTreeList } from '@/api/employingUnit'
import { filterBtn, recordBtn } from '@/util/roles'
const columns = [
  {
    title: '活动名称',
    dataIndex: 'name',
    key: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '发布时间',
    dataIndex: 'dateCreated',
    key: 'dateCreated',
    scopedSlots: { customRender: 'dateCreated' }
  },
  {
    title: '状态',
    width: 120,
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
const operateBtn = [{
  name: 'candidateApplication.publish',
  status: 'status',
  statusValN: ['NEW', 'REVOKE'],
  id: 'NEW'
}, {
  name: 'candidateApplication.revoke',
  status: 'status',
  statusValN: ['PUBLISHED'],
  id: 'PUBLISHED',
  class: 'red'
}]
const searchListArr = [
  // {
  //   id: 'name',
  //   type: 'input',
  //   name: '姓名'
  // }, {
  //   id: 'email',
  //   type: 'input',
  //   name: '邮箱'
  // }, {
  //   id: 'phone',
  //   type: 'input',
  //   name: '电话'
  // }
  // {
  //   id: 'enterpriseId',
  //   type: 'input',
  //   name: '单位'
  // }
  // {
  //   id: 'status',
  //   type: 'select',
  //   name: '状态',
  //   values: [{ id: 'ENABLE', name: '启用' }, { id: 'DISABLE', name: '禁用' }]
  // }
]

export default {
  name: 'AcctTable',
  components: { TableOperate, SearchFiled },
  props: ['data', 'pagination', 'loading', 'selectedRowKeys', 'forbidControl', 'overWriteColumns'],
  data () {
    return {
      moment,
      acctList: [],
      visible: false,
      filterBtn,
      recordBtn,
      columns: this.overWriteColumns || columns.filter(item => item.key !== 'company'),
      searchListArr: searchListArr.filter(item => this.$store.state.user.userInfo.role === 'ROLE_VENDOR' ? item.id !== 'status' : true),
      operateBtn,
      from: '',
      deliverDate: '',
      searchField: {},
      searchFieldTmp: {},
      valueFileds: null,
      rejectVisible: false,
      rejectIds: [],
      rejectReason: ''
    }
  },
  created () {
    // this.getTreelist()
    if (this.$route.name === 'activityList') {
      columns[0].title = '活动名称'
    } else {
      columns[0].title = '名称'
    }
  },
  computed: {
    getBtn () {
      let isAllPublished = true
      let isAllRevoke = true
      let arr = []
      if (this.selectedRowKeys.length > 0 && !this.forbidControl) {
        arr = this.data.filter(t => this.selectedRowKeys.includes(t.id))
        arr.forEach(t => {
          if (t.status !== 'NEW' && t.status !== 'REVOKE') {
            isAllPublished = false
          }
          if (t.status !== 'PUBLISHED') {
            isAllRevoke = false
          }
        })
      }
      if (this.selectedRowKeys.length > 0 && !this.forbidControl && (this.$store.state.user.userInfo.role === 'ROLE_ADMIN' || this.$store.state.user.userInfo.role === 'ROLE_HRBP')) {
        if (isAllPublished) {
          return this.operateBtn.slice(0, 1)
        }
        if (isAllRevoke) {
          return this.operateBtn.slice(1)
        }
      }
      return null
    }
  },
  methods: {
    // async getTreelist () {
    //   // this.loading = true
    //   // this.selectedRowKeys = []
    //   let params = {
    //     status: ''
    //   }
    //   let res = await selectTreeList(params)
    //   if (res.code === 200) {
    //     let arr = []
    //     arr = resizeTree(res.data)
    //     this.searchListArr.some(element => {
    //       if (element.id === 'enterpriseId') {
    //         element.treeData = arr
    //         return true
    //       }
    //     })
    //   } else {
    //     this.$message.error(res.message)
    //   }
    //   if (this.$route.query.enterpriseId) { // 职位界面跳转过来
    //     this.valueFileds = {
    //       enterpriseId: this.$route.query.enterpriseId
    //     }
    //   }
    //   // this.loading = false
    // },
    closeOneField (id) {
      // if (!this.valueFileds) {
      this.valueFileds = {}
      // }
      this.$set(this.valueFileds, id, '')
    },
    onSelectChange (selectedRowKeys, acctList) {
      this.acctList = acctList
      this.$emit('setSelected', selectedRowKeys)
      // this.selectedRowKeys = selectedRowKeys
    },
    clearSearch () {
      this.$refs.TableOperate.clearSearch()
    },
    // 批量
    async updateStatus (status, ids) {
      if (status === 'NEW' || status === 'REVOKE') {
        this.updateAuditStatus('PUBLISHED', ids)
      } else if (status === 'PUBLISHED') {
        this.updateAuditStatus('REVOKE', ids)
      }
      // this.updateAuditStatus(status, ids)
    },
    // 发布 或 下线
    updateAuditStatus (status, ids) {
      let prams = null
      prams = ids.map(id => {
        return { status, id }
      })
      console.info(prams)
      let fn = null
      if (this.$route.name === 'activityList') {
        fn = changeActivityStatus
      } else if (this.$route.name === 'imgsList') {
        fn = changePicStatus
      } else if (this.$route.name === 'videoList') {
        fn = changeVideoStatus
      } else if (this.$route.name === 'introList') {
        fn = changeIntroStatus
      } else if (this.$route.name === 'institutionList') {
        fn = changeInstitutionStatus
      }
      this.$confirm({
        title: `是否确定${status === 'PUBLISHED' ? '发布' : '下线'}？`,
        onOk: async () => {
          let res = await fn(prams)
          if (res.code === 200) {
            this.$message.success('操作成功')
            let pagination = this.pagination
            pagination.current = 1
            this.$emit('update', { searchField: this.searchFieldTmp, pagination })
          } else {
            this.$message.error(res.message)
          }
        },
        onCancel () {
        },
        class: 'test'
      })
    },
    searchFormValue (searchField) {
      this.searchFieldTmp = searchField
      let searchFieldTmp = JSON.parse(JSON.stringify(searchField))
      this.searchField = searchFieldTmp
      searchFieldTmp.key = searchFieldTmp.keyword
      delete searchFieldTmp.keyword
      let pagination = this.pagination
      pagination.current = 1
      this.$emit('update', { searchField: searchFieldTmp, pagination })
    },
    changePage (current, pageSize) {
      let pagination = this.pagination
      pagination.current = current
      this.$emit('update', { searchField: this.searchField, pagination })
    },
    setRowClassName (record, index) {
      return index % 2 !== 0 ? 'grey' : ''
    },
    getCheckboxProps (record) {
      console.info(record)
      return {
        props: {
          // disabled: record.status === 'NEW'
          disabled: false
        }
      }
    },
    // 去活动详情页
    toDetail (record) {
      console.info(record)
      if (this.$route.name === 'activityList') {
        this.$router.push(`/activity/activityDetail?id=${record.id}`)
      } else if (this.$route.name === 'introList') {
        this.$router.push(`/intro/introDetail?id=${record.id}`)
      } else if (this.$route.name === 'videoList') {
        this.$router.push(`/video/videoDetail?id=${record.id}`)
      } else if (this.$route.name === 'institutionList') {
        this.$router.push(`/institution/institutionDetail?id=${record.id}`)
      } else if (this.$route.name === 'imgsList') {
        this.$router.push(`/imgs/imgsDetail?id=${record.id}`)
      }
    },
    toActivityEdit (id) {
      if (this.$route.name === 'activityList') {
        this.$router.push('/activity/activityEdit?id=' + id)
      } else if (this.$route.name === 'introList') {
        this.$router.push('/intro/introEdit?id=' + id)
      } else if (this.$route.name === 'videoList') {
        this.$router.push('/video/videoEdit?id=' + id)
      } else if (this.$route.name === 'institutionList') {
        this.$router.push('/institution/institutionEdit?id=' + id)
      } else if (this.$route.name === 'imgsList') {
        this.$router.push('/imgs/imgsEdit?id=' + id)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.AcctTable
  :global(.top)
    padding 14px 18px!important
  background #fff
  .errorColor
    color errorColor
  .grey
    color textGrey
  .green
    color lightGreen
  // 表格头部公共写法
  // :global(.ant-table-title)
  //   padding 0
  // :global(.ant-table-thead th)
  //   background none
  //   padding 0
  // :global(.ant-table-thead .ant-table-header-column)
  //   display inline-block
  //   width calc(100% - 16px)
  //   padding 5px 8px
  //   margin 5px 8px
  //   border-right 1px solid borderColor
  // :global(.ant-table-thead th:first-child .ant-table-header-column)
  // :global(.ant-table-thead th:last-child .ant-table-header-column)
  //   border-right none
  // :global(.ant-table-tbody >tr >td)
  //   padding 7px 16px
  //   vertical-align top
  :global(.grey)
    background var(--light-grey)
  .updateText
    margin 0
    font-weight 600
  .update
    // visibility hidden
    margin 6px 0 0
    span
      // display none
      // display inline-block
      cursor pointer
      // border-right 1px solid borderColor
      padding 0
      color var(--blue-500)
      &.red
        color errorColor
      &:first-child
        padding-left 0
      &:last-child:after
        height 0
        // color errorColor
      &:after
        content ''
        vertical-align middle
        background borderColor
        display inline-block
        height 14px
        width 1px
        margin-left 4px
  // :global(.ant-table-row)
  //   margin 0 12px
  // :global(.ant-table-row:hover)
  //   :global(td)
  //   .update
  //     >span
  //       display inline-block
      // visibility visible
.ant-table.ant-table-bordered .ant-table-title
  border none
::v-deep .ant-table-row
  border-bottom 1px solid borderColor
.expand_wrap
  font-size 12px
</style>
